<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/login.css">
    <link rel="stylesheet" href="css/base.css">
    <title>登录页面</title>
</head>

<body>
    <div class="container">
        <div class="login-wrapper">
            <div class="header">登录</div>
            <div class="form-wrpper">
                <input type="text" class="input-item" id="username" placeholder="请输入用户名">
                <input type="password" class="input-item" id="password" placeholder="请输入密码">
                <button>立即登录</button>
            </div>
            <div class="msg">
                <a href="register.html">没有账号？立即注册</a>
            </div>
        </div>
    </div>
    <script src="js/alert.js"></script>
    <script>
        const btn = document.querySelector('button')
        const username = document.querySelector('#username')
        const password = document.querySelector('#password')
        btn.addEventListener('click', function() {
            var xhr = new XMLHttpRequest()
                //以POST方法发送请求，第二个参数为请求地址
            xhr.open("POST", "http://localhost:8081/user/login", true)
                //设置请求头
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
                //用'&’隔开参数
            xhr.send(`username=${username.value}&password=${password.value}&token=''`)
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        let info = JSON.parse(xhr.response)
                        if (info.data.token) {
                            localStorage.setItem('token', info.data.token)
                            window.location.href = 'index.html'
                            console.log(JSON.parse(xhr.responseText))
                        } else {
                            Toast('用户名或密码错误', 1000)
                            console.log(JSON.parse(xhr.responseText))
                        }
                    }
                }
            }
        })
    </script>
</body>

</html>